use crate::{tool_convert, tool_result::Error};
use chrono::{Local, NaiveDateTime, TimeZone};
use std::time::{SystemTime, UNIX_EPOCH};

///日期时间工具
#[derive(Debug, Clone)]
pub struct DateTime {
    pub time: chrono::DateTime<Local>,
}

impl DateTime {
    pub fn now() -> Self {
        DateTime { time: Local::now() }
    }
    ///完整的时间格式
    pub fn to_str_full(&self) -> String {
        self.time.format("%Y-%m-%d %H:%M:%S").to_string()
    }
    pub fn to_str_full_nospace(&self) -> String {
        self.time.format("%Y-%m-%d-%H-%M-%S").to_string()
    }
    ///获取年月日字符串
    pub fn to_str(&self) -> String {
        self.time.format("%Y-%m-%d").to_string()
    }
    pub fn to_datetime(str: &str) -> Result<Self, Error> {
        // 定义日期字符串和格式
        let format = "%Y-%m-%d %H:%M:%S";

        let date_time = match chrono::NaiveDateTime::parse_from_str(str, format) {
            Ok(date) => date,
            Err(e) => {
                return Err(Error::new(format!("{}日期格式错误:{}", str, e)));
            }
        };

        Ok(DateTime {
            time: Self::naive_to_local(date_time),
        })
    }
    fn naive_to_local(naive: NaiveDateTime) -> chrono::DateTime<Local> {
        // 将 NaiveDateTime 转换为 DateTime<Local>
        Local.from_local_datetime(&naive).unwrap()
    }
    ///获取时间戳 毫秒
    pub fn get_time_timestamp_mill() -> u128 {
        let start = SystemTime::now();
        // 获取自 Unix 纪元以来的时间
        let since_the_epoch = start
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards");

        since_the_epoch.as_millis()
    }
    ///大于目标时间多少秒
    /// DateTime::to_datetime("2024-11-3 21:24:00")?.get_diff_time_sec(&DateTime::to_datetime("2024-11-3 21:25:00")?) =-60
    pub fn get_diff_time_sec(&self, time: &Self) -> i64 {
        // 计算两个时间点的差
        let duration: chrono::Duration = self.time.signed_duration_since(time.time);
        // 输出差值（秒）
        duration.num_seconds()
    }
    ///获取和目标时间相差多少秒 效果和c#的datetime一样
    pub fn get_diff_time_mill(&self, time: &Self) -> i64 {
        // 计算两个时间点的差
        let duration: chrono::Duration = self.time.signed_duration_since(time.time);
        // 输出差值（秒）
        duration.num_milliseconds()
    }
    ///添加秒
    pub fn add_sec(&mut self, sec: i64) {
        let time = self.time + chrono::Duration::seconds(sec);
        self.time = time;
    }
    ///获取现在的小时 分钟
    pub fn get_hour_minute() -> (u64, u64) {
        let hm = Local::now().format("%H:%M").to_string();
        let hm_list: Vec<&str> = hm.split(":").collect();
        (
            tool_convert::StringConvert::to_int_u64(hm_list[0]).unwrap(),
            tool_convert::StringConvert::to_int_u64(hm_list[1]).unwrap(),
        )
    }
}
